<template>
  <a-drawer
    class="container-set"
    v-model:visible="visible"
    title="组件配置"
    placement="right"
    :maskClosable="false"
    width="650"
  >
    <a-form class="m-form-box" :model="formState" :rules="formRules" ref="form">
      <a-form-item label="key" name="">
        <a-input v-model:value="formState.key" disabled />
      </a-form-item>
      <a-form-item label="组件名" name="">
        <a-input v-model:value="formState.component" disabled />
      </a-form-item>
      <a-form-item label="标题" name="title">
        <a-input v-model:value="formState.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="栅格大小" name="span">
        <a-input-number v-model:value="formState.span" />
      </a-form-item>
      <a-form-item label="有子路由" v-if="hasSecond && secondContainerList.length">
        <a-switch v-model:checked="formState.hasChildRoute" />
      </a-form-item>
      <a-form-item label="组件属性" name="componentProps">
        <a-textarea :rows="4" v-model:value="formState.componentProps" :placeholder="$getText('PH_CUSTOM_PROPS')" />
      </a-form-item>
      <a-form-item label="样式" name="styles">
        <a-textarea :rows="4" v-model:value="formState.styles" :placeholder="$getText('PH_CUSTOM_CSS')" />
      </a-form-item>

      <a-form-item label="绑定详情" name="">
        <a-button type="primary" @click="bindComponent" :disabled="!hasDetail">
          {{ hasDetail ? '新增详情' : '未勾选详情组件' }}
        </a-button>
      </a-form-item>
      <div v-for="(item, index) in formState.detailConfig" :key="index" class="detail-box">
        <DetailForm :detailForm="item" ref="detailForm" @delete="deleteComponent(item)"></DetailForm>
      </div>
    </a-form>

    <template #extra>
      <a-space>
        <a-button type="primary" @click="handleSave">保存</a-button>
      </a-space>
    </template>
  </a-drawer>

  <!-- 选择组件 -->
  <a-modal v-model:visible="componentVisible" title="选择组件" width="80%" destroyOnClose @ok="handleOk">
    <component-list ref="componentList" isView componentType="2" />
  </a-modal>
</template>

<script>
/**
 * 页面配置 - 布局容器的配置
 * @author 朱琦
 * @date   时间：2023/2/1
 */

import DetailForm from './DetailSet.vue'
// import ComponentList from '../../../component-manage/components/ComponentList.vue'
import ComponentList from '../../../component-manage/index.vue'
import { mapGetters } from 'vuex'
import { validatorJsonPromise } from '@/views/management/utils/validate'

// 表单默认字段
const defaultForm = {
  key: null,
  component: null,
  title: null,
  span: 6,
  hasChildRoute: false,
  componentProps: '',
  styles: null,
  detailConfig: []
}

export default {
  name: 'ComponentSet',
  props: {},
  components: { DetailForm, ComponentList },
  emits: ['submit'],
  data() {
    return {
      formState: {},
      formRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        span: [{ required: true, message: '请输入栅格大小', trigger: 'blur' }],
        styles: [{ required: false, validator: validatorJsonPromise, trigger: 'blur' }],
        componentProps: [{ required: false, validator: validatorJsonPromise, trigger: 'blur' }]
      },
      visible: false,
      componentVisible: false
    }
  },
  computed: {
    ...mapGetters({
      pageType: 'page-manage-config/pageType',
      containerList: 'page-manage-config/containerList'
    }),
    // 详情容器列表
    detailContainerList() {
      return this.containerList.filter(i => i.type === 'detail')
    },
    // 二级组件（代表走子路由）容器列表
    secondContainerList() {
      return this.containerList.filter(i => i.type === 'second')
    },
    hasDetail() {
      return this.pageType.includes('detail')
    },
    hasSecond() {
      return this.pageType.includes('second')
    }
  },
  watch: {
    visible: {
      handler(newValue, oldValue) {
        if (!newValue) {
          this.formState.detailConfig = []
          defaultForm.detailConfig = []
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    /**
     * 显示
     * @param {Object} data 修改时的数据
     */
    show(data) {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.setData(data)
      })
    },
    /**
     * 关闭
     */
    hide() {
      this.visible = false
    },
    /**
     * 设置表单数据
     * @param {Object} data
     */
    setData(data = defaultForm) {
      Object.keys(defaultForm).forEach(key => {
        if (key === 'detailConfig' && data[key]) {
          this.formState[key] = [...data[key]]
          return
        }
        this.formState[key] = data[key] || defaultForm[key]
      })
      this.formState.componentProps = this.formState.componentProps ? JSON.stringify(data.componentProps) : ''
      this.formState.styles = this.formState.styles ? JSON.stringify(data.styles) : null
    },
    /**
     * 点击保存
     */
    handleSave() {
      const promiseArr = []
      if (this.$refs.detailForm) {
        this.$refs.detailForm.forEach((item, index) => {
          this.formState.detailConfig[index] = {
            title: this.formState.detailConfig[index].componentName,
            ...item.detailFormState
          }
          promiseArr.push(item.$refs.form.validate())
        })
      }
      promiseArr.push(this.$refs.form.validate())
      Promise.all(promiseArr).then(res => {
        const form = {}
        Object.keys(this.formState).forEach(key => {
          if (key == 'detailConfig' && this.formState[key] && this.formState[key].length) {
            this.formState[key].map(i => {
              i.componentProps = i.componentProps ? JSON.parse(i.componentProps) : ''
              i.styles = i.styles ? JSON.parse(i.styles) : ''
              return i
            })
          }
          form[key] = this.formState[key]
        })
        form.componentProps = this.formState.componentProps ? JSON.parse(this.formState.componentProps) : ''
        form.styles = this.formState.styles ? JSON.parse(this.formState.styles) : null
        this.$emit('submit', form)
        this.hide()
      })
    },

    /**
     * 选择组件 完成
     */
    handleOk() {
      const data = this.$refs.componentList.getSelectData()
      const repeat = this.formState.detailConfig.findIndex(item => item.id == data.id)
      if (repeat > -1) return this.$message.warning('已存在重复组件，请重新勾选')
      this.formState.detailConfig.push(data)
      this.componentVisible = false
    },

    /**
     * 点击绑定组件
     */
    bindComponent() {
      if (!this.detailContainerList.length) {
        return this.$message.warning('请添加详情组件的布局容器后再绑定详情组件！')
      }
      this.componentVisible = true
    },

    /**
     * 删除绑定的组件
     */
    deleteComponent(item) {
      const index = this.formState.detailConfig.findIndex(i => i.id == item.id)
      this.formState.detailConfig.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="less">
@import url(../../../../assets/styles/form.less);
.container-set {
}
</style>
